<template>
  <div class="form_box">
    <el-form :model="dataForm" :rules="dataFormRules" ref="dataForm" label-width="100px" class="demo-ruleForm">
      <!-- k -->
      <!-- <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username"></el-input>
      </el-form-item> -->
      
      <el-form-item label="账号名" prop="account">
        <el-input v-model="dataForm.account" placeholder="账号名用于登录"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <MUserPasswordInput @onDataChanged="onPasswordChanged"></MUserPasswordInput>
        <!-- <el-input v-model="dataForm.account"></el-input> -->
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username"></el-input>
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input v-model="dataForm.phone"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email"></el-input>
      </el-form-item>

      <el-form-item label="权限角色" prop="availableRole">
        <MUserRoleSelect @onDataChanged="onRoleChanged"></MUserRoleSelect>
      </el-form-item>

      <!-- 确认 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm()" :loading="loading">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from 'vuex'
import { MUserPasswordInput,MUserRoleSelect } from './impl'
import { muserAddApi } from '@/manager-core/api/muser/muser'
import { ElMessage } from 'element-plus'


export default defineComponent({
  name: 'MUserAdd',

  components: {
    MUserPasswordInput,
    MUserRoleSelect
  },

  data(){
    return {      
      dataForm : {
        account: '',
        username: '',
        password: '',
        ptype: 0,
        email: '',
        phone: '',
        isadmin: true,
        roleids: [],
        pwdisdefault: true,
        availableRole: false,
        availablePassword: false
      },
      dataFormRules: {
        account: [
          {required:true,message: '请输入account',trigger: 'blur'}
        ],
        password: [
          {required:true,validator: this.checkPasswordAvalable,message: '请输入password',trigger: 'blur'}
        ],
        username: [
          {required:true,message: '请输入username',trigger: 'blur'}
        ],
        availableRole: [
           {required:true, validator: this.checkRoleAvalable  ,message: '请选择角色',trigger: 'blur'}
        ]
      },
      loading : false      
    }
  },

  methods:{
    init(){

    },

    onPasswordChanged(data:any){
      this.dataForm.ptype = data.ptype;
      this.dataForm.password = data.password;
    },

    onRoleChanged(data:any){
      this.dataForm.isadmin = data.isadmin;
      this.dataForm.roleids = data.roleids;
    },

    checkPasswordAvalable(){
      if(this.dataForm.ptype == 0){
        return true;
      }
      else if (this.dataForm.password){
        return true;
      }
      return false;
    },

    checkRoleAvalable(){
      if(this.dataForm.isadmin){
        return true;
      }
      else if (this.dataForm.roleids && this.dataForm.roleids.length > 0){
        return true;
      }
      return false;
    },

    submitForm(){
      (this.$refs['dataForm'] as any)
      .validate((valid:any)=>{
        if(valid){
          // 验证通过
          console.log("submitForm success")

          this.loading = true;

          muserAddApi(this.dataForm)
            .then(()=>{
                ElMessage.success("创建成功！");
            })
            .finally(()=>{
              this.loading = false;
              (this.$refs['dataForm'] as any).resetFields();
            })

        }
        else{
          // 未验证通过
          ElMessage.error("未通过表单验证，请检查表单项");
        }
      })
    }
  },

  mounted(){
    console.log("muser")
  },

  setup(){
    // const store = useStore()

    // return {
    //   LoginByUsername:(userObj:any)=> store.dispatch('LoginByUsername')
    // }

  }


})


// @Component
// export default class Login extends BaseVue {
//   @Action("LoginByUsername", { namespace }) LoginByUsername: any;
//   username: string = "";
//   password: string = "";
//   error: string = "";
//   loading: boolean = false;
//   redirect: string = "";
//   isPhone = false;
//   getCodeText: any = "获取验证码";
//   changeText = "手机验证码登录";
//   userPhone = ""; //手机号
//   codeText = ""; //验证码
//   canClick = true;
//   $message: any;
//   $router: any;
//   $alert: any;
//   login() {
//     if (this.username == null || this.username.length == 0) {
//       this.error = "请填写用户名！";
//       return;
//     }

//     this.loading = true;

//     const lf = {
//       u: this.username,
//       p: this.password,
//     };
//     // this.$router.push({ path: '/' });
//     this.LoginByUsername(lf)
//       .then(() => {
//         store.commit("profileModule/DelTabsInfo", [
//           {
//             path: "/dashboard",
//             query: {},
//             title: "首页",
//           },
//         ]);
//         this.$router.push({ path: "/" });
//       })
//       .catch((error: any) => {
//         console.log(error);
//       })
//       .finally(() => {
//         this.loading = false;
//       });
//   }

//   // 使用手机验证码登陆
//   phoneLogin() {
//     let phone = this.userPhone;
//     if (!/^1[3456789]\d{9}$/.test(phone)) {
//       this.error = "手机号码有误，请重填！";
//       return false;
//     }
//     if (!this.codeText) {
//       this.error = "请输入验证码！";
//       return false;
//     }
//     let code = this.codeText;
//     let data = {
//       phone,
//       code,
//     };
//     phoneLoginApi(data)
//       .then((res: any) => {
//         if (res.code == 0) {
//           this.$message.error(res.message);
//         }
//       })
//       .catch((error) => {
//         console.log(error);
//       });
//   }

//   forget() {
//     this.$alert("请直接联系管理人员获得密码！", "忘记密码", {
//       showConfirmButton: false,
//       closeOnClickModal: true,
//     });
//   }
//   // 更改登录方式
//   changePage() {
//     this.isPhone = !this.isPhone;
//     this.error = "";
//     if (!this.isPhone) {
//       this.changeText = "手机验证码登录";
//     }
//     if (this.isPhone) {
//       this.changeText = "用户名密码登录";
//     }
//   }
//   // 获取验证码
//   getCode() {
//     let phone = this.userPhone;
//     let _this: any = this;
//     if (!/^1[3456789]\d{9}$/.test(phone)) {
//       this.error = "手机号码有误，请重填！";
//       return false;
//     }
//     if (this.canClick) {
//       this.canClick = false;
//       let phone = _this.userPhone;
//       // 验证码接口
//       getCodeApi(phone)
//         .then((res) => {
//           console.log(123, res);
//         })
//         .catch((error) => {
//           console.log(error);
//         });
//       this.getCodeText = 60;
//       let CodeInterval = setInterval(() => {
//         if (this.getCodeText > 0) {
//           this.getCodeText -= 1;
//         } else {
//           clearInterval(CodeInterval);
//           this.canClick = true;
//           this.getCodeText = "重新获取验证码";
//         }
//       }, 1000);
//     }
//   }

// }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>

</style>
